const Controller = require('egg').Controller;

class ChatController extends Controller {
    async chat() {
        const { ctx } = this;
        const { messages } = ctx.request.body;

        try {
            console.log('ctx.service.openai',ctx.service.openai)
            // 使用 OpenAI 服务
            const stream = await ctx.service.openai.chatCompletion(messages);

            // 设置响应头
            ctx.set('Content-Type', 'text/event-stream');
            ctx.set('Cache-Control', 'no-cache');
            ctx.set('Connection', 'keep-alive');

            // 处理流式数据
            for await (const part of stream) {
                const delta = part.choices[0]?.delta?.content;
                if (delta) {
                    ctx.res.write(`data: ${JSON.stringify({ content: delta })}\n\n`);
                }
            }

            // 结束响应
            ctx.res.end();
        } catch (error) {
            console.log(error)
            // 错误处理
            let errorMessage = error.message;
            let statusCode = error.status || 500;

            // 处理常见错误
            switch (error.code || error.type) {
                case 'ETIMEDOUT':
                case 'ESOCKETTIMEDOUT':
                case 'timeout_error':
                    errorMessage = '请求超时，请稍后再试';
                    statusCode = 504;
                    break;
                case 'ECONNREFUSED':
                case 'connection_error':
                    errorMessage = '无法连接到 OpenAI 服务，请检查网络';
                    statusCode = 503;
                    break;
                case 'rate_limit_error':
                    errorMessage = '请求频率超限，请稍后再试';
                    statusCode = 429;
                    break;
                case 'invalid_request_error':
                    errorMessage = '请求参数错误';
                    statusCode = 400;
                    break;
                case 'authentication_error':
                    errorMessage = 'API 认证失败，请检查配置';
                    statusCode = 401;
                    break;
            }

            // 记录错误
            ctx.logger.error('[Chat] Error handling request', {
                error: {
                    name: error.name,
                    message: error.message,
                    code: error.code,
                    type: error.type,
                    status: error.status
                },
                response: error.response?.data
            });

            ctx.status = statusCode;
            ctx.body = {
                success: false,
                error: errorMessage,
                details: process.env.NODE_ENV === 'development' ? {
                    code: error.code,
                    type: error.type,
                    response: error.response?.data
                } : null
            };

            // 确保流式响应正确结束
            if (!ctx.res.writableEnded) {
                ctx.res.end();
            }
        }
    }
}

module.exports = ChatController;
